package com.my.study.controller;

import com.my.study.redisson.constant.ServerInfoConstants;
import com.my.study.redisson.constant.TaskConstants;
import com.my.study.redisson.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: yidujun
 * @create: 2021/08/12 20:23
 */
@Slf4j
@RestController
@RequestMapping("/redisson")
public class RedissonController {

    @Resource
    RedissonClient redissonClient;

    @RequestMapping("/lock")
    public void lock() {
        String lockKey = System.nanoTime() + "ydj";
        RLock lock = redissonClient.getLock(lockKey);

        System.out.println(ServerInfoConstants.SERVER_NO);

        ServerInfoConstants.SERVER_NO = "1";

        System.out.println(ServerInfoConstants.SERVER_NO);

        boolean tryLock = lock.tryLock();
        if (tryLock) {
            log.info("### 加锁成功...");
            try {
                log.info("逻辑处理>>>>>>>>");
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                    log.info("### 释放锁成功...");
                }
            }
        }
    }


    @RequestMapping("/publish")
    public void publish() throws InterruptedException {
        while (true) {
            RMap<String, Date> serverList = redissonClient.getMap(TaskConstants.SERVER_LIST);
            for (Map.Entry<String, Date> entry : serverList.entrySet()) {
                log.info("[publish]服务列表 ip:port={}, expire={}", entry.getKey(), entry.getValue());
            }

            RMap<String, Long> serverListNo = redissonClient.getMap(TaskConstants.SERVER_LIST_NO);
            for (Map.Entry<String, Long> entry : serverListNo.entrySet()) {
                log.info("[publish]服务编号 ip:port={}, no={}", entry.getKey(), entry.getValue());
            }

            log.info("==================================================================");
            TimeUnit.SECONDS.sleep(5);
        }

    }
}
